<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <div v-if="isShow && !disabled && isUpload" class="editor-custom-btn-container">
      <editorImage :tinymceinfo="tinymceinfo" :type="type" color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div>
  </div>
</template>

<script>
import editorImage from './components/EditorImage'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
import {debounce} from 'throttle-debounce'
// 预留功能插件
import plugins from './plugins'
const tinymceCDN = 'https://mall-filepool.oss-cn-hangzhou.aliyuncs.com/system/tinymce5/tinymce.min.js'
export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    type: {
      type: String,
      required: false,
      default: () => ''
    },
    height: {
      type: Number,
      required: false,
      default: 360
    },
    tinymceinfo: {
      type: Object,
      required: false,
      default: () => {}
    },
    id: {
      type: String,
      default: function() {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    isUpload: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  data() {
    return {
      newValue: '',
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      isShow: true
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      this.$emit('changeVal', val)
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
    }
  },
  mounted() {
    // this.isShow = this.$route.query.isShow == 'true' ? true : false
    this.isShow = true
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    initTinymce() {
      this.newValue = this.value
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        language: 'zh_CN',
        forced_root_block: '',
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: true,
        toolbar: this.isShow && !this.disabled ? toolbar : '',
        menubar: false,
        end_container_on_empty_block: true,
        paste_data_images: true,
        powerpaste_word_import: 'propmt',
        powerpaste_html_import: 'propmt',
        powerpaste_allow_local_images: true,
        code_dialog_height: 450,
        code_dialog_width: 1000,
        statusbar: false,
        force_br_newlines: false,
        force_p_newlines: false,
        remove_trailing_brs: true,
        convert_fonts_to_spans: false,
        extended_valid_elements: 'span',
        image_dimensions: true,
        content_style: 'img{max-width:50%}',
        plugins: 'image imagetools',
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        image_advtab: true,
        imagetools_cors_hosts: ['www.tinymce.com', 'aliyuncs.com', 'ibeeking.com', 'localhost'],
        imagetools_credentials_hosts: ['www.tinymce.com', 'aliyuncs.com', 'ibeeking.com', 'localhost'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true,
        readonly: this.isShow && !this.disabled ? '' : 1,
        init_instance_callback: editor => {
          if (_this.newValue) {
            editor.setContent(_this.newValue)
            this.vModel(editor)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        images_upload_handler(blobInfo, success, failure, progress) {
          console.log(blobInfo, success, failure, progress)
        }
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
      })
    },
    vModel(editor) {
        // 控制连续写入时setContent的触发频率
        const debounceSetContent = debounce(250, editor.setContent)
        this.$watch('value', (val, prevVal) => {
            if (editor && val !== prevVal && val !== editor.getContent()) {
                if (typeof val !== 'string') val = val.toString()
                debounceSetContent.call(editor, val)
            }
        })

        editor.on('change keyup undo redo', () => {
            this.$emit('input', editor.getContent())
        })
        editor.on('blur', () => {
            this.$emit('blur')
        })
    },
  }
}
</script>

<style scoped>
.tinymce-container {
  width: 100%;
  position: relative;
  line-height: normal;
}
.tinymce-container>>>.mce-fullscreen {
  z-index: 10000;
}
.tinymce-container>>>.tox-toolbar__group {
  padding-right: 100px;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 1;
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}

</style>
